import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import * as path from 'path'
import eslintPlugin from 'vite-plugin-eslint'
import Components from 'unplugin-vue-components/vite'
import AutoImport from 'unplugin-auto-import/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import Icons from 'unplugin-icons/vite'
import IconsResolver from 'unplugin-icons/resolver'
import { FileSystemIconLoader } from 'unplugin-icons/dist/loaders.js'
import { visualizer } from 'rollup-plugin-visualizer'
import YKResolver from './src/@yk/resolver'
import { UrlConfig } from './src/settings'

// 自定义图标集
const iconCustom = IconCustomCollections()

// https://vitejs.dev/config/
export default defineConfig({
  define: {
    // 允许打包开发环境使用process.env变量
    'process.env': process.env
  },
  css: {
    preprocessorOptions: {
      scss: {
        additionalData: '@use "@yk/styles/colors/global.scss" as *;'
      }
    }
  },
  plugins: [
    vue(),
    Icons({
      compiler: 'vue3',
      customCollections: iconCustom.Collections
    }),
    Components({
      resolvers: [
        ElementPlusResolver({ importStyle: false }),
        iconCustom.ComponentsResolver,
        YKResolver()
      ]
    }),
    AutoImport({
      imports: [
        'vue', 'vue-router', {
          'element-plus': ['ElMessageBox', 'ElMessage', 'ElLoading', 'ElNotification']
        }
      ],
      resolvers: [
        ElementPlusResolver()
      ],
      eslintrc: { enabled: true }
    }),
    eslintPlugin({
      include: ['src/**/*.js', 'src/**/*.vue', 'src/*.js', 'src/*.ts', 'src/**/*.ts', 'src/*.vue']
    }),
    // 包分析工具
    visualizer({ open: true })
  ],
  resolve: {
    alias: {
      '@': path.join(__dirname, './src'),
      '@assets': path.join(__dirname, './src/assets'),
      '@images': path.join(__dirname, './src/assets/images'),
      '@utils': path.join(__dirname, './src/utils'),
      '@typings': path.join(__dirname, './src/typings'),
      '@views': path.join(__dirname, './src/views'),
      '@yk': path.join(__dirname, './src/@yk')
    },
    extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue']
  },
  server: {
    host: '0.0.0.0',
    port: 5166,
    proxy: {
      '/dev': {
        target: UrlConfig.development.BASE_URL,
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/dev/, '')
      }
    }
  },
  base: './',
  build: {
    assetsDir: 'static',
    minify: 'terser',
    terserOptions: {
      compress: {
        // 清理console和debugger（minify需为terser）
        drop_console: false,
        drop_debugger: true
      }
    },
    rollupOptions: {
      output: BuildOutput()
    }
  }
})

// region TODO 自定义图标集
function IconCustomCollections () {
  const collections = ['system', 'traffic', 'menu', 'device', 'data', 'bor', 'video']

  // 文件解析器
  function getFileSystemIconLoader (dir) {
    return FileSystemIconLoader(dir, svg => svg.replace(/^<svg /, '<svg width="1em" height="1em" fill="currentColor" '))
  }

  return {
    ComponentsResolver: IconsResolver({
      prefix: 'ic',
      customCollections: collections
    }),
    Collections: collections.reduce(function (collections, key) {
      collections[key] = getFileSystemIconLoader('./src/assets/icons/' + key)
      return collections
    }, {})
  }
}

// endregion

// region TODO 自定义打包规则
function BuildOutput () {
  // 静态资源分类
  const assetFileConfig: Record<string, string[]> = {
    img: ['svg', 'png', 'jpg', 'jpeg', 'gif', 'webp'],
    fonts: ['otf', 'ttf']
  }
  // 需要独立打包的资源
  const manualChunksNames = ['element-plus', 'axios', 'moment', 'echarts', 'amap', 'ezuikit-js']

  const _assetFileConfig: Record<string, string> = {}
  for (const type in assetFileConfig) {
    const typeList = assetFileConfig[type]
    for (let i = 0, len = typeList.length; i < len; i++) {
      _assetFileConfig[typeList[i]] = type
    }
  }
  return {
    // 分包（分片）名称
    chunkFileNames ({ name }) {
      if (manualChunksNames.includes(name)) {
        return `static/js/chunk-${name}.[hash].js`
      }
      return 'static/js/chunk-[hash].js'
    },
    // 静态资源名称
    assetFileNames ({ name }) {
      let fileType = '[ext]'
      const lastIndex = name.lastIndexOf('.')
      if (lastIndex > -1) {
        const ext = name.substring(lastIndex + 1).toLocaleLowerCase()
        _assetFileConfig[ext] && (fileType = _assetFileConfig[ext])
      }
      return `static/${fileType}/[name].[hash].[ext]`
    },
    // 分包（分片）规则
    manualChunks (id: string) {
      if (id.includes('node_modules')) {
        const chunkName = id.toString().split('node_modules/')[1].split('/')[0].toString()
        return manualChunksNames.includes(chunkName) ? chunkName : undefined
      }
    },
    entryFileNames: 'static/js/app.[hash].js'
  }
}

// endregion
